<template>


  <view @longpress="longpress" style="height: 100vh;">
  
    <!-- 选择状态 -->
    <view class="choose" v-if="operate">
      <span style="color:#39a9ed;font-weight:600; " @click="SelectAll">{{allChoose?'全不选':'全选'}}</span>
      <span style="font-weight: 600;">已选择{{quantity}}项</span>
      <span @click="chooseCancel" style=" font-weight:600;color:#39a9ed;">取消</span>
    </view>
    <!-- 单词本封面 -->
    <view class="word-book-cover" :style="bground">
      <image :src="options.wordBookCover" mode=""></image>
      <text>{{options.wordBookName}}</text>
    </view>
    <u-empty mode="car" v-if="!words.length" icon="http://cdn.uviewui.com/uview/empty/car.png"  text="长按添加单词"  textSize="35"  iconSize="45" >    </u-empty>
    <!-- 学习进度暂时弃用 -->
    <!-- <view class="progress">
      <view style="color: green;">
        <p>23</p>
        <p>已掌握</p>
      </view>
      <view style="color: #27c5f5;">
        <p>23</p>
        <p>已学</p>
      </view>
      <view style="color: #a10101;">
        <p>23</p>
        <p>未学</p>
      </view>
    </view> -->
    <!-- 单词 -->
    <!-- 单词列表，可以封装一个虚拟列表 -->
    <view style="padding-bottom: 500rpx;">
      <WordList ref="child" @allChooseBoolean="allChooseBoolean" :words="words" :operate="operate" />
    </view>
    <!-- 长按选择事件 -->
    <view class="operate" v-if="operate">
      <!-- 分享   (本来想用css的var变量来实现选中时的透明度变化的，但是有BUG实现不了)-->
      <view @click="share" :style="quantity?'opacity:1':'opacity:0.2'">
        <span class="iconfont">&#xe8b1; </span>
        <text>分享</text>
      </view>
      <!-- 复制 -->
      <view @click="imports">
        <span class="iconfont">&#xe8b0;</span>
        <text>导入</text>
      </view>
      <!-- 新增 -->
      <view @click="addWord">
        <span class="iconfont">&#xe600; </span>
        <text>新增</text>
      </view>
      <!-- 移动 （暂未开发） -->
      <!--  <view style="opacity:0.2">
        <span class="iconfont">&#xe601; </span>
        <text>移动</text>
      </view> -->
      <!-- 删除 -->
      <view @click="Delete" :style="quantity?'opacity:1':'opacity:0.2'">
        <span class="iconfont">&#xe718;</span>
        <text>删除</text>
      </view>




    </view>
    <!-- 新增单词弹窗层 -->
    <view>
      <van-dialog use-slot title="添加单词" :show="show" show-cancel-button :before-close="onBeforeClose" zIndex="109"
        @close="close">
        <van-field :value="wordForm.word" @change="wordName" :border="false" label="单词名字" placeholder="请输入单词名字" />
        <van-field :value="wordForm.translation" @change="formTranslation" :border="false" label="单词释义"
          placeholder="请输入单词释义" />
        <van-radio-group :value="wordForm.collection" @change="onChange" direction="horizontal">
          <span class="starBooksText" style="margin-right: 1.5rem;">收藏单词本</span>
          <van-radio name="0" class="starText">不收藏</van-radio>
          <van-radio name="1" class="starText">收藏</van-radio>
        </van-radio-group>
        <van-field type="textarea" custom-style="margin-top:10rpx;padding-right:30rpx;height:600rpx"
          :autosize="{ 'minHeight': 400}" :value="wordForm.paraphrase" @change="textarea" maxlength="-1"
          placeholder="请输入单词详细释义" />
      </van-dialog>

    </view>
    <!-- 导入单词 -->
    <van-dialog zIndex="109" use-slot title="导入单词" :show="importShow" show-cancel-button id="van-dialog"
      :before-close="improtBeforeClose" @close="importClose">
      <van-field type="textarea" custom-style="margin-top:10rpx;padding-right:30rpx;height:250rpx"
        :autosize="{ 'minHeight': 200}" :value="wordKey" @change="textareakey" maxlength="-1" placeholder="请输入导入单词密钥" />
    </van-dialog>
    <!-- 导入的单词列表 -->
    <u-modal style="height: 600rpx;overflow-y: auto;" :show="selectImport" :title="title" :content='content'
      showCancelButton="true" @cancel="importCancel" @confirm="importConfirm">
      <ImportWordsList :words="importwordList"></ImportWordsList>
    </u-modal>

    <!-- 消息通知 -->
    <van-notify id="van-notify" style="z-index: 2001 !important;" />
  </view>
</template>

<script>
  import Notify from '@/wxcomponents/vant/notify/notify';
  import {
    nextTick
  } from "vue";
  export default {
    data() {
      return {
        bground: '--bground: url(http://cdn.zhoukaiwen.com/JavaScript.jpg)',
        opacitys: '--opacitys:0.2',
        // 单词本名字
        options: {
          // 单词本图片
          wordBookCover: null,
          // 单词本id
          id: null,
          // 伪元素背景
          wordBookName: null
        },
        // 单词数据
        words: [],
        operate: false, //操作栏变量
        show: false, //控制新增单词弹窗  
        wordForm: {
          word: null, //单词
          translation: null, //单词翻译
          paraphrase: null, //单词释义
          collection: '0', //收藏 1 为收藏 0 为未收藏 默认为0未收藏
          dept_id: null, //单词本id
        },
        // 全选状态
        allChoose: false,
        // 选择的数量
        quantity: 0,
        // 导入单词密钥
        wordKey: '复制这段内容粘贴到源码单词导入功能[&U2FsdGVkX19WMjTyTEnacH6G4BuJwhZx//qp1wbTb2k=&]即可获取',
        //控制导入单词弹窗
        importShow: false,
        // 导入的单词列表
        importwordList: null,
        // 控制选择导入单词框
        selectImport: false,

      };
    },
    methods: {
      // 获取单词数据
      async getBooks() {
        let id = {
          id: this.options.id
        }

        const res = await uni.$myRequest('/home/word/getWord', 'GET', id)
        console.log(res.data.data)
        this.words = res.data.data
      },
      // 控制新增按钮的弹窗
      addWord() {
        this.show = true
      },
      // 添加单词
      async bookConfirm() {
        console.log('确定')
        // 复制这段内容粘贴到源码单词导入功能[&U2FsdGVkX18+tLmwN+knC17uWS27urnC7BwB3OjXBC8=&]即可获取


        let res = await uni.$myRequest('/home/word/addWords', 'POST', this.wordForm)


        this.getBooks()
        console.log(res)
      },

      // 监听长按事件
      longpress() {
        this.operate = true
        console.log(this.operate, 777)
      },
      // 操作状态全选
      SelectAll() {
        this.$refs.child.checkAll()
      },
      // 改变操作全选和不全选的字   
      allChooseBoolean(Boolean, quantity) {
        this.allChoose = Boolean
        this.quantity = quantity
      },
      // 操作状态取消
      chooseCancel() {
        this.operate = false
        this.$refs.child.check()
      },
      // 分享单词
      share() {
        // 如果有选中单词，就调用子组件事件
        if (this.quantity) {
          this.$refs.child.shareWords()
        }
      },
      // 添加单词弹窗的点击取消和确认的事件(vant真他妈难用)
      onBeforeClose(action) {
        //因为onBeforeClose无法获取this,所以使用getCurrentPages（获取当前页面栈）来获取data
        const pages = getCurrentPages()
        // page就是当前页面
        let page = pages[pages.length - 1]
        return new Promise((resolve) => {
          if (action === 'confirm') {
            let boolean = false
            // 判断单词名字是否重复
            page.data.words.find((value, index, arr) => {
              if (value.word == page.data.wordForm.word) {
                boolean = true
              }
            })
            if (!page.data.wordForm.word) {
              Notify({
                type: 'danger',
                message: '请输入单词名字',
                duration: 1500,
              });
              return resolve(false);
            }
            if (!page.data.wordForm.translation) {
              Notify({
                type: 'danger',
                message: '请输入单词释义',
                duration: 1500,
              });
              return resolve(false);
            } else if (!page.data.wordForm.paraphrase) {
              console.log(page.data.wordForm.paraphrase, 'page.data.wordForm.paraphrase')
              Notify({
                type: 'danger',
                message: '请输入单词详细释义',
                duration: 1500,
              });
              return resolve(false);
            }
            // 新增单词
            page.$vm.bookConfirm()
          }
          resolve(true);
        })

      },
      // 导入其它单词弹窗
      async imports() {
        this.importShow = true
        // let data = {
        //   id: [65],
        //   dept_id: 56
        // }
        // const res = await uni.$myRequest('/home/word/importWords', 'POST', data)
        // console.log(res, 'res')
      },
      // 新增单词弹框的关闭事件
      close() {
        console.log(this.wordForm, '.wordForm')
        // Object.assign()常用来拷贝合并对象,相同属性替换，不同属性新增
        this.wordForm = Object.assign(this.wordForm, {
          word: null,
          translation: null,
          paraphrase: null
        })


        this.show = false

      },
      // 下面四个方法是新增单词本input赋值 （vant因为BUG问题后续会弃用，这部分需要优化）
      // 删除选中的单词
      Delete() {
        // 调用子组件的事件
        this.$refs.child.Delete()
      },
      wordName(event) {
        this.wordForm.word = event.detail
      },
      formTranslation(event) {
        this.wordForm.translation = event.detail
      },
      onChange(event) {
        this.wordForm.collection = event.detail
      },
      textarea(event) {
        this.wordForm.paraphrase = event.detail
      },
      // 导入密钥赋值
      textareakey(event) {
        this.wordKey = event.detail
      },
      // 导入单词弹窗的点击取消和确认的事件(vant真他妈难用)
      improtBeforeClose(action) {
        //因为onBeforeClose无法获取this,所以使用getCurrentPages（获取当前页面栈）来获取data
        const pages = getCurrentPages()
        // page就是当前页面
        let page = pages[pages.length - 1]
        return new Promise((resolve) => {
          if (action === 'confirm') {
            if (!page.data.wordKey) {
              Notify({
                type: 'danger',
                message: '请输入单词密钥',
                duration: 1500,
              });
              return resolve(false);
            }
            // 点击确认时，把内容正则过滤，再发送给后端
            const pattern = /\&(.*?)\&/g;
            let matches = page.data.wordKey.match(pattern);
            let results = matches ? matches.map(match => match.slice(1, -1)) : [];
            console.log(results[0], 'zhengze');
            let data = {
              key: results[0]
            }


            uni.$myRequest('/home/word/importWords', 'POST', data).then(res => {
              if (res.data.status === 201) {
                uni.showToast({
                  title: '密钥错误',
                  icon: "error"
                })
              }
              page.$vm.importWords(res)
            })

          }
          resolve(true);
        })
      },
      // 新增单词弹框的关闭事件
      importClose() {
        this.wordKey = ''
        this.importShow = false
      },
      // 导入单词
      importWords(res) {

        this.importwordList = res.data.data
        this.selectImport = true
        console.log(res, 666)
      },
      // 导入单词弹窗关闭
      importCancel() {
        this.selectImport = false
      },
      // 确定导入按钮事件
      async importConfirm() {
        let data = {
          data: JSON.stringify(this.importwordList),
          dept_id: this.options.id
        }
        let res = await uni.$myRequest('/home/word/importWordsOut', 'POST', data)
        this.getBooks()
        this.selectImport = false
      }
    },

    onLoad(options) {
      // 开发测试的BUG,onLoad的事件只会触发一次,重新编译就不会赋值
      try { //如果options的数据异常，json就会报错，这时就可以利用这点来操作
        this.options = JSON.parse(options.data)
        //把值存储在本地  
        uni.setStorageSync('options', this.options)
      } catch (e) {
        // 捕捉json的报错，用来正确存储options数据 
        this.options = uni.getStorageSync("options")
      }
      this.bground = `--bground: url(${this.options.wordBookCover})`
      // 直接传链接会发送乱码问题,使用decodeURIComponent即可解决(该问题已优化，删除部分代码)
      this.wordForm.dept_id = this.options.id
      this.getBooks()
    }
  }
</script>

<style lang="scss" scoped>
  .word-book-cover {
    position: relative;
    width: 100%;
    height: 13.5rem;

    &:before {
      content: '';
      position: absolute;
      top: -1%;
      left: 0;
      width: 100%;
      height: 12rem;
      // background:url(http://cdn.zhoukaiwen.com/JavaScript.jpg);
      background: var(--bground);
      z-index: -1;
      background-repeat: no-repeat;
      background-size: 100% 100%;
      opacity: 0.7;
      filter: blur(10px);
      overflow: hidden;
    }

    image {
      width: 7rem;
      height: 7rem;
      border: 4px solid white;
      border-radius: 5%;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      box-shadow: 0 0 20px 0.5px #dbe0e0;
    }

    text {
      position: absolute;
      left: 50%;
      top: 81%;
      transform: translate(-50%);
      color: white;
      -webkit-text-stroke: 1px saddlebrown;
      font-weight: 700;
      font-size: 1.8rem;
    }
  }

  .progress {
    height: 4rem;
    display: flex;
    justify-content: space-around;
    align-items: center;
    font-size: 1.2rem;
    text-align: center;
    font-weight: 700;
    box-shadow: 0 0.3px 13px 0.3px #e2e1e1;
  }

  .choose {
    position: fixed;
    z-index: 99; //开启固定定位后,点击事件会失效,需要提高层级
    top: 0;
    height: 70rpx;
    width: 100%;
    background-color: white;
    font-size: 35rpx;
    display: flex;
    justify-content: space-between;
    border: 1px solid #eaeeee;

    span {
      text-align: center;
      line-height: 70rpx;
      width: 180rpx;
    }
  }

  .operate {
    width: 20rem;
    height: 4rem;
    position: fixed;
    left: 50%;
    bottom: 6rem;
    transform: translate(-50%, 0%);
    border-radius: 10px;
    background-color: white;
    border: 1px solid #eaeeee;
    display: flex;
    justify-content: space-evenly;
    align-content: center;

    view {
      width: 20%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;

      span {
        font-size: 50rpx
      }

      text {
        font-size: 25rpx
      }
    }
  }



  van-field {
    /deep/ .van-cell {
      padding: 7rpx 0 7rpx 32rpx;
    }

  }

  .starBooksText {
    color: #646566;
    font-size: 0.9rem;
    margin: 2% 5% 0% 5%;
  }

  van-radio {
    z-index: 999;
  }

  .starText {
    margin: 2% 0% 0% 0%;
    color: #646566;
    font-size: 0.9rem;
  }
</style>
